'use strict';

const fs = require('fs');
const { sequelize } = require('../db');

function searchModelsFiles() {
    // 搜索当前文件所有目录，找出所有js文件，并且不是index.js的文件
    let files = fs.readdirSync(__dirname);
    return files.filter(name => {
        return name.endsWith('.js') && name !== 'index.js';
    })
}

// 将所有定义的模型，暴露出来
function registerModels(files) {
    let obj = {};
    files.forEach(name => {
        let modelName = name.substring(0, name.length - 3);
        obj[modelName] = require(__dirname + '/' + name);
    });
    return obj;
}

let files = searchModelsFiles();
let obj = registerModels(files);

obj.sync = async (opt) => {
    if (process.env.NODE_ENV !== 'production') {
        return sequelize.sync({ force: true });
    } else {
        throw new Error('当环境变量设置生产环境时，无法调用sync函数进行初始化数据库操作');
    }

}

module.exports = obj;